<template>
    <van-sticky>
        <van-nav-bar :title="product.name" left-text="返回" left-arrow @click-left="onBack" />
    </van-sticky>

    <van-image width="100%" height="500" fit="cover" :src="product.thumbs_cdn" />

    <div class="detailbox">
        <h4>{{ product.name }}</h4>
        <div class="price">
            商品起步价：<em>￥</em>{{ product.price }}
        </div>
    </div>

    <div class="allkbox"></div>

    <!-- 商品规格 -->
    <div class="info_choice">
        <!-- Sku 商品规格 -->
        <div class="commodity" @click="SkuShow = true">
            <div class="opt">
                <div class="title wanl-gray">选择</div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>尺码</span>
                            |
                            <span>颜色</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
        <!-- 服务 -->
        <div class="commodity" @click="TipShow = true">
            <div class="opt">
                <div class="title wanl-gray">服务</div>
                <div class="option">
                    <div class="selected">
                        <div>
                            <span>7天无理由退款</span>
                            <span>·</span>
                            <span>24小时内发货</span>
                            <span>·</span>
                            <span>假一赔十</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="wanl-gray">
                <img src="/assets/images/go.png" />
            </div>
        </div>
    </div>

    <div class="allkbox"></div>

    <!-- 选项卡 -->
    <van-tabs v-model:active="TabActive" type="card" color="#EE0A24">
        <van-tab title="产品参数">
            <div style="text-align: center" v-html="product.content"></div>
        </van-tab>
        <van-tab title="商品评价">
            <div class="rate" style="overflow-x: hidden">
                <div class="rate-header">
                    <div class="rate-score">
                        <h4>与描述相符</h4>
                        <strong>4.5</strong>
                    </div>
                    <div class="rate-graph">
                        <van-rate v-model="rate" allow-half readonly />
                    </div>
                </div>

                <div class="rate-content">
                    <div>
                        <div class="review-box">
                            <div class="review-item">
                                <!-- 评论人 -->
                                <div class="from-whom">
                                    <div class="avatar">
                                        <img src="/assets/images/avatar.png" />
                                    </div>
                                    <div class="name">暂无昵称</div>
                                </div>

                                <!-- 评论内容 -->
                                <div class="review-details">
                                    <div class="content">评论内容</div>
                                    <div>
                                        <img src="/assets/images/avatar.png" />
                                    </div>
                                    <div class="time">2024-07-30</div>
                                    <van-rate v-model="rate" readonly />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div>
                        <div class="rate-empty">该商品还没有人写评价呢</div>
                    </div>
                </div>
            </div>
        </van-tab>
    </van-tabs>

    <!-- 协议条款 -->
    <van-action-sheet v-model:show="TipShow" title="协议条款">
        <div class="ProductTip">
            三、我们如何使用信息 <br />
            四、我们如何共享信息<br />
            五、我们如何转让信息<br />
            六、我们如何公开披露信息<br />
            七、一般储存期限<br />
            八、我们如何确保您的信息安全<br />
            九、您能做什么<br />
            十、我们如何处理未成年人的个人信息<br />
            十一、您的个人信息的存储地点<br />
            十二、本隐私权政策不适用的范围<br />
            十三、本隐私权政策如何更新<br />
            十四、联系我们<br />
        </div>
    </van-action-sheet>

    <!-- SKU -->
    <van-sku ref="SkuRef" v-model="SkuShow" :sku="sku" :properties="properties" :goods="goods" :goods-id="product.id"
        @add-cart="onAddCart" @buy-clicked="onBuy">
        <template #sku-actions="props">
            <div class="van-sku-actions">
                <van-button square size="large" type="warning"
                    @click="props.skuEventBus.emit('sku:addCart')" >加入购物车</van-button>

                <!-- 直接触发 sku 内部事件，通过内部事件执行 onBuyClicked 回调 -->
                <van-button square size="large" type="danger"
                    @click="props.skuEventBus.emit('sku:buy')">单独购买</van-button>
            </div>
        </template>
    </van-sku>

    <div style="height: 60px;"></div>

    <!-- 底部导航栏 -->
    <van-action-bar>
        <router-link to="/chat">
        <van-action-bar-icon icon="chat-o" text="客服" />
        </router-link>
        <van-action-bar-icon icon="cart-o" text="购物车" />
        <van-action-bar-icon :icon="isCollected ? 'star' : 'star-o'" :text="isCollected ? '取消收藏' : '收藏'"
            @click="toggleCollect" />
        <van-action-bar-button type="danger" text="立即购买" @click="SkuShow = true"/>
    </van-action-bar>
</template>

<script setup>
import VanSku from 'vant-sku';
import 'vant-sku/dist/index.css';

const { proxy } = getCurrentInstance();

const product = ref({});
const business = proxy.$business;
const proid = ref(proxy.$route.query.proid ?? 0);


const isCollected = ref(false);
// 商品sku
const SkuShow = ref(false);// 显示该商品规格
const TipShow = ref(false);// 是否显示协议条款弹出层
const TabActive = ref(0);// 用于控制显示产品参数或者商品评论
const rate = ref(4.5);// 商品综合评分
const comment = ref([]);// 当前商品的所有评论
const SkuRef = ref(null);// 组件实例 类似id用法
const sku = ref({});// 商品规格数据
const goods = ref({});// 商品信息
const properties = ref([]);// 商品属性

onBeforeMount(() => {
    getProductInfo();
})

const toggleCollect = async () => {
    if (!business.value.id || Object.getOwnPropertyNames(business.value).length === 0) {
        SkuShow.value = false;

        proxy.$confirm({
            title: '登录',
            message: '是否跳转登录界面？'
        }).then(() => {
            proxy.$stores.redirect = {
                path: '/product/info',
                params: {
                    proid: proid.value
                }
            };
            proxy.$router.push({
                path: '/business/login',
                // replace:true
            })
        }).catch((err) => { });
    }else{


        let params = {
            collectid: proid.value,
            busid: business.value.id
        }
        let result = await proxy.$http.post({
            url: '/product/collection',
            params
        })

        if (result.code === 1) {
            isCollected.value = result.data
            proxy.$success({
                message: result.msg,
            })

        } else {
            proxy.$warning({
                message: result.msg,
                onClose: () => {

                }
            })
        }
    }
}

const getProductInfo = async () => {
    let params = {
        proid: proid.value,
        busid: business.value.id
    }

    let result = await proxy.$http.post({
        url: '/product/info',
        params
    })


    if (result.code === 1) {
         isCollected.value = result.data.product['collection_status']
        sku.value = result.data.sku;
        properties.value = Object.values(result.data.properties);
        product.value = result.data.product;

        goods.value = {
            picture: product.value.thumbs_cdn
        };

    } else {
        proxy.$warning({
            message: result.msg,
            onClose: () => {
                onBack();
            }
        })
    }
}

const onAddCart = async (values) => {
    
    if(!business.value.id || Object.getOwnPropertyNames(business.value).length === 0)
    {
        SkuShow.value = false;

        proxy.$confirm({
            title:'登录',
            message:'是否跳转登录界面？'
        }).then(() => {
            proxy.$stores.redirect = {
                path:'/product/info',
                params:{
                    proid:proid.value
                }
            };
            proxy.$router.push({
                path:'/business/login',
                replace:true
            })
        }).catch((err) => {});
    }
    else
    {
        if(properties.value.length > 0 && !values.selectedSkuComb)
        {
            proxy.$fail('请选择商品规格');

            return false;
            
        }

        // 商品属性关联
        let relationids = [];

        if(properties.value.length > 0 && values.selectedSkuComb)
        {
            for(let item of values.selectedSkuComb.properties)
            {
                relationids.push(item.v[0].id);
            }
        }

        let params = {
            busid:business.value.id,
            proid:proid.value,
            pronum:values.selectedNum,
            relationids:relationids.join(',')
        }
        
        let result = await proxy.$http.post({
            url:'/cart/add',
            params
        })

        if(result.code === 1)
        {
            SkuShow.value = false;

            proxy.$confirm({
                title:'加入购物车成功',
                message:'是否跳转购物车进行结算？'
            }).then(() => {
                
                proxy.$router.push({
                    path:'/cart',
                    query:{action:'info'}
                })
            }).catch((err) => {});
        }else{
            proxy.$fail(result.msg);
        }
    }

}

// 单独购买
const onBuy = (values) => {

    
    if (
        !business.value.id ||
        Object.getOwnPropertyNames(business.value).length === 0
    ) {
        SkuShow.value = false;
        loginOrNot();
    } else {
        if (properties.value.length > 0 && !values.selectedSkuComb) {
            proxy.$fail("请选择商品规格");

            return false;
        }

        // 商品属性关联
        let relationids = [];

        if (properties.value.length > 0 && values.selectedSkuComb) {
            for (let item of values.selectedSkuComb.properties) {
                relationids.push(item.v[0].id);
            }
        }

        let params = {
            action: 'buyone',
            proid: proid.value,
            pronum: values.selectedNum,
            relationids: relationids.join(","),
        };
        proxy.$router.push({ path: "/order/confirm", query: { ...params } });
    }
};

const onBack = () => proxy.$router.back();
</script>

<style scoped>
@import url('/assets/css/ProductInfo.css');
</style>